#!/usr/bin/env bash
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -eu

if [[ "$#" -ne 3 ]]; then
  echo 2>"Usage: $(basename "$0") <year> <prefix> <destination-directory>"
  exit 1
fi

readonly YEAR="${1}"
readonly PREFIX="${2}"
readonly DEST="${3}"

mkdir -p "${DEST}/buildpack/bin"

print_boilerplate() {
  cat <<_EOF_
# Copyright ${YEAR} Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#
# DO NOT EDIT: automatically generated by ./ci/generate-builder.sh
#

_EOF_
}

(
  print_boilerplate
  cat <<_EOF_
[[buildpacks]]
uri = "buildpack"

[[order]]
    [[order.group]]
    id = "com.google.buildpack.cpp"
    version = "0.6.0"

# Stack that will be used by the builder
[stack]
id = "google"
run-image   = "${PREFIX}run-image:latest"
build-image = "${PREFIX}build-image:latest"
_EOF_
) >"${DEST}/builder.toml"

(
  print_boilerplate
  cat <<_EOF_
api = "0.2"

[buildpack]
id = "com.google.buildpack.cpp"
version = "0.6.0"
name = "Functions Framework C++ Buildpack (prefix=${PREFIX})"

[[stacks]]
id = "google"
_EOF_
) >"${DEST}/buildpack/buildpack.toml"

(
  echo '#!/bin/bash'
  print_boilerplate
  cat <<_EOF_
set -eu

if ! (compgen -G "*.cc" >/dev/null ||
  compgen -G "*.cpp" >/dev/null ||
  compgen -G "*.cxx" >/dev/null ||
  [[ ! -f CMakeLists.txt ]]); then
  exit 100
fi

exit 0
_EOF_
) >"${DEST}/buildpack/bin/detect"
chmod 755 "${DEST}/buildpack/bin/detect"

(
  echo '#!/bin/bash'
  print_boilerplate
  cat "$(dirname "$0")/build.in"
) >"${DEST}/buildpack/bin/build"

chmod 755 "${DEST}/buildpack/bin/build"
